package mail.fetch.aliyun;

import mail.util.CookieParser;
import mail.util.JsInvoker;
import mail.util.RegexSearcher;
import mail.util.UnZipper;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.han.http.util.Print.printlnInfo;

/**
 * @Author: Hanjiafeng
 * @Date: 2019-1-22 14:44:27
 * @Desc: 登录阿里云邮箱
 */
@Deprecated
public class Login {
    private Map<String, String> cookieRepository;
    private String username;
    private String password;

    public Login(String username, String password) {
        this.username = username;
        this.password = password;
        cookieRepository = new HashMap<>();
    }

    private void simulateRequest() throws Exception {
        //初始化HttpClient.Builder
        HttpClient.Builder clientBuilder = HttpClient.newBuilder();
        //初始化HttpClient
        HttpClient client = clientBuilder.build();
        //初始化HttpRequest.Builder
        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                .timeout(Duration.ofMinutes(1))
                .setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
                .setHeader("Accept-Encoding", "gzip, deflate, br")
                .setHeader("Accept-Language", "zh-CN,zh;q=0.9")
                //.setHeader("Upgrade-Insecure-Requests", "1")
                .setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
        //定义HttpRequest
        HttpRequest request;

        //获取主页及其cookies
        /*request = requestBuilder
                .uri(URI.create("https://mail.aliyun.com"))
                .build();
        HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());*/

        //mini_ login
        request = requestBuilder
                .uri(URI.create("https://cnpassport.alibaba.com/mini_login.htm?lang=zh_CN&appName=yunmail&appEntrance=default&styleType=auto&bizParams=&notLoadSsoView=true&notKeepLogin=true&isMobile=false&rnd=0.5219248565897212"))
                .setHeader("Referer", "https://mail.aliyun.com")
                .build();
        HttpResponse<byte[]> byteResponse = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
        //解析body中存在的加密秘钥和post参数
        String body = new String(UnZipper.unGzipByBytes(byteResponse.body()));
        String umidToken = RegexSearcher.matchFirst(body, "(?<=umidToken\"[\\s]{0,10}value=\")((?!\").)*(?=\")");
        String csrfToken = RegexSearcher.matchFirst(body, "(?<=_csrf_token\"[\\s]{0,10}value=\")((?!\").)*(?=\")");
        String rsaKey1 = RegexSearcher.matchFirst(body, "(?<=modulus\"[\\s]{0,10}value=\")((?!\").)*(?=\")");
        String rsaKey2 = RegexSearcher.matchFirst(body, "(?<=exponent\"[\\s]{0,10}value=\")((?!\").)*(?=\")");
        String hsid = RegexSearcher.matchFirst(body, "(?<=hsid\"[\\s]{0,10}value=\")((?!\").)*(?=\")");

        //解析cookie
        HttpHeaders httpHeaders = byteResponse.headers();
        Map<String, List<String>> currentMap = httpHeaders.map();
        CookieParser.parseList(cookieRepository, currentMap.get("Set-Cookie"));

        //etag
        request = requestBuilder
                .uri(URI.create("https://log.mmstat.com/eg.js"))
                .setHeader("Referer", "https://mail.aliyun.com/")
                .build();
        HttpResponse<String> stringResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
        httpHeaders = stringResponse.headers();
        currentMap = httpHeaders.map();
        CookieParser.parseList(cookieRepository, currentMap.get("Set-Cookie"));

        //checkAccount
        String postDataStr = "loginId=" + username +
                "&appName=yunmail" +
                "&appEntrance=default" +
                "&bizParams=" +
                "&hsid=" + hsid +
                "&rdsToken=" +
                "&umidToken=" + umidToken +
                "&isRequiresHasTimeout=false" +
                "&isRDSReady=true" +
                "&isUMIDReady=true" +
                "&umidGetStatusVal=255" +
                "&lrfcf=" +
                "&lang=zh_CN" +
                "&scene=" +
                "&isMobile=false" +
                "&screenPixel=1920x1080" +
                "&navlanguage=zh-CN" +
                "&navUserAgent=Mozilla%2F5.0+(Windows+NT+10.0%3B+Win64%3B+x64)+AppleWebKit%2F537.36+(KHTML%2C+like+Gecko)+Chrome%2F71.0.3578.98+Safari%2F537.36" +
                "&navAppVersion=" +
                "&navPlatform=Win32" +
                "&_csrf_token=" + csrfToken;
        HttpRequest.BodyPublisher postData = HttpRequest.BodyPublishers.ofString(postDataStr);
        //生成cookie
        String cookie = "cookie2=" + cookieRepository.get("cookie2") +
                ";t=" + cookieRepository.get("t") +
                ";_tb_token_=" + cookieRepository.get("_tb_token_") +
                ";_uab_collina=" + System.currentTimeMillis() + "92140771001" +
                ";cna=" + cookieRepository.get("cna") +
                ";isg=" + "BE9PkJ8HTwDlq0t8mc5jj76D3uOZ3LPwNS1CHWFct77FMGwyY0Qk5uliNiArSHsO";
        request = requestBuilder
                .uri(URI.create("https://cnpassport.alibaba.com/newlogin/account/check.do?fromSite=-2&appName=yunmail"))
                .setHeader("Accept", "undefined")
                .setHeader("Origin", "https://cnpassport.alibaba.com")
                .setHeader("Referer", "https://cnpassport.alibaba.com/mini_login.htm?lang=zh_CN&appName=yunmail&appEntrance=default&styleType=auto&bizParams=&notLoadSsoView=true&notKeepLogin=true&isMobile=false&rnd=0.7947528477988821")
                .setHeader("Cookie", cookie)
                .setHeader("X-Requested-With", "XMLHttpRequest")
                .POST(postData)
                .build();
        byteResponse = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
        body = new String(UnZipper.unGzipByBytes(byteResponse.body()));
        printlnInfo(body);

        //login.do
        String encryptedPwd = encrypt(rsaKey1, rsaKey2);
        //生成post数据
        postDataStr = "loginId=" + username +
                "&password2=" + encryptedPwd +
                "&checkCode=" +
                "&appName=yunmail" +
                "&appEntrance=default" +
                "&bizParams=" +
                "&ua=115%236GV14f1O1TZvhR2MGCFD1CsoE51GBwPw1g4yRtXt85%2BlVoXffxZi62ZyDx1CI%2BVA1aU8o9PcaTC9yzEQogOPeKT8ukNp7IvJhUU75WCra8pf11jQvIAyetT8yWKpggiNLf78OkNcZLMXurrpO7U3s%2BQ4ukNZi%2FJRh6b8OkNDah2fuzFQASAPe1L8ykNQOQDPsA9vVNHXPV9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JIuw0RCCRPkZwgydSfEUYGru4JSbyshpyW4BAZ31ZnWngSjddsLWN%2FMWDoX4%2FvU64lzAKkE%2FmUo9%2B1OFo9BWJ7SOYw456TNjmF1s821XhBj95RKILL8%2BHI7rhlEmrshjazt7qMYmELLv909PSUZPkeK3b7v1cAd3zGzBKvEgxm5LH32kepOG17hvsFuFcA5gZJLHc1bWoBnYJ38gMWzP8CDGTaxGpK9l41qzn6v6L1OCvfI1cIooFGU9o54tQ%2FgoHZKoDNKlqHbE8N%2BvPQBZN5Fge3S6nvIIy0EoicLLaY2XIGMqiDyTSKUyK0gRC7OtA%2Bv6joFHMGT3pI%2BHlfWSozIX3kaBGlPgWo1lNwkX1HdFOzw1R%3D" +
                "&hsid=" + hsid +
                "&rdsToken=" +
                "&umidToken=" + umidToken +
                "&isRequiresHasTimeout=false" +
                "&isRDSReady=true" +
                "&isUMIDReady=true" +
                "&umidGetStatusVal=255" +
                "&lrfcf=" +
                "&lang=zh_CN" +
                "&scene=" +
                "&isMobile=false" +
                "&screenPixel=1920x1080" +
                "&navlanguage=zh-CN" +
                "&navUserAgent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" +
                "&navAppVersion=" +
                "&navPlatform=Win32" +
                "&token=" +
                "&nocAppKey=" +
                "&csessionid=" +
                "&sig=" +
                "&captchaToken=" +
                "&_csrf_token=" + csrfToken;
        postData = HttpRequest.BodyPublishers.ofString(postDataStr);
        request = requestBuilder
                .uri(URI.create("https://cnpassport.alibaba.com/newlogin/login.do?fromSite=-2&appName=yunmail"))
                .setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .setHeader("Origin", "https://cnpassport.alibaba.com")
                .setHeader("Referer", "https://cnpassport.alibaba.com/mini_login.htm?lang=zh_CN&appName=yunmail&appEntrance=default&styleType=auto&bizParams=&notLoadSsoView=true&notKeepLogin=true&isMobile=false&rnd=0.654234748339005")
                .setHeader("Cookie", cookie)
                .POST(postData)
                .build();
        byteResponse = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
        body = new String(UnZipper.unGzipByBytes(byteResponse.body()));
        printlnInfo(body);
        httpHeaders = byteResponse.headers();
        printlnInfo(httpHeaders);
    }

    /**
     * 密码加密
     *
     * @param rsaKey1 秘钥1
     * @param rsaKey2 秘钥2
     * @return 加密后的密码
     */
    private String encrypt(String rsaKey1, String rsaKey2) {
        String filePath = "F:\\workspace\\java\\MailCrawler\\src\\main\\resources\\EncryptAliyun.js";
        String method = "encrypt('" + rsaKey1 + "','" + rsaKey2 + "','" + password + "')";

        return JsInvoker.invokeJs(method, filePath);
    }
}
